package com.lizheng.yunservice.wx.controller;

import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import com.lizheng.yunservice.common.domain.ApiRestResponse;
import com.lizheng.yunservice.wx.domain.bo.WxUserLoginBo;
import com.lizheng.yunservice.wx.domain.vo.Code2SessionVo;
import com.lizheng.yunservice.wx.service.MinProgramService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 47967
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/wx/user")
public class WxMaUserController {
    private final MinProgramService minProgramService;

    /**
     * 微信小程序登录
     */
    @PostMapping("/login")
    public ApiRestResponse<Code2SessionVo> login(HttpServletRequest request, @RequestBody WxUserLoginBo loginBo) {
        try {
            log.error("微信登录: {}", loginBo);
            Code2SessionVo code2SessionVo = minProgramService.code2Session(request, loginBo);
            return ApiRestResponse.ok(code2SessionVo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return ApiRestResponse.fail("解析jcCode失败！");
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
    }
}
